<template>
  <div v-if="visible">
    <div
      style="
        text-align: center;
        position: absolute;
        top: 0;
        background: rgba(2, 35, 51, 0.749);
        z-index: 1;
        padding: 0 12px;
        left: 50%;
        transform: translateX(-50%);
        border-end-start-radius: 32px;
        border-end-end-radius: 32px;
      "
    >
      <el-checkbox-group v-model="showAirGridTypes">
        <el-checkbox
          v-for="type in airGridTypes"
          :key="type"
          :label="`第${type}层`"
          :value="type"
          style="--el-checkbox-text-color: #fff"
        />
      </el-checkbox-group>
    </div>

    <!-- <vc-entity v-for="grid in airGrids" :key="grid.id" :position="getPosition(grid)" @click="handleOpen(grid)">
			<vc-graphics-box :dimensions="getDimensions(grid)" :material="grid.areoTypeColor"
				:outline-color="grid.areoTypeColor" :outline="true"></vc-graphics-box>
		</vc-entity> -->

    <!-- 渲染 Primitive -->
    <vc-primitive
      :key="primitiveKey"
      :appearance="primitiveAppearance"
      :geometryInstances="geometryInstances"
      @click="handleFocus"
    />

    <vc-entity :position="getPosition(form)" @click="handleBlur" v-if="form">
      <vc-graphics-box
        :dimensions="getDimensions(form)"
        outline-color="#ff9008"
        :outline="true"
        material="#ff9008"
      ></vc-graphics-box>
    </vc-entity>

    <vc-overlay-html
      ref="html"
      :position="getPosition(form)"
      :show="true"
      v-if="form"
    >
      <div
        style="
          color: #fff;
          padding: 6px 12px;
          line-height: 14px;
          font-size: 13px;
          background: rgba(2, 35, 51, 0.749);
        "
      >
        <div style="text-align: right">
          <el-space>
            <el-icon :size="16" @click="handleEdit" style="cursor: pointer"
              ><Edit
            /></el-icon>
            <el-icon :size="16" @click="handleBlur" style="cursor: pointer"
              ><Close
            /></el-icon>
          </el-space>
        </div>
        <p>网格编号: {{ form.code }}</p>
        <p>
          网格坐标: {{ `${form.longitude},${form.latitude},${form.height}` }}
        </p>
        <p>网格等级: {{ `第${form.gridClass}级` }}</p>
        <p>所属层级: {{ `第${form.layer}层` }}</p>
        <p>网格容量: {{ `${form.capacity}架次/小时` }}</p>
        <p>网格流量: {{ `${form.flow}架次/小时` }}</p>
        <p>拥挤等级: {{ form.congestion }}</p>
        <p>网格类型: {{ form.areoTypeName }}</p>
        <p>空域网联环境: {{ form.env }}</p>
        <p>噪音: {{ form.noise }}DB</p>
        <p>风速: {{ form.speed }}米/秒</p>
        <p>风险: {{ form.risk }}</p>
        <p>费用: {{ form.cost >= 20 ? form.cost : 20 + form.cost }}元</p>
        <p>人口密度: {{ form.people * 50 }}人/平方公里</p>
        <p>拥挤等级: {{ form.congestion }}</p>
        <p>作业类型: {{ form.activity }}</p>
      </div>
    </vc-overlay-html>

    <el-drawer
      v-model="drawerVisible"
      :show-close="false"
      :size="500"
      v-if="form"
      class="airgrid-edit-drawer"
    >
      <template #header>
        <span class="el-drawer__title">{{ `网格编号：${form.code}` }}</span>
        <div class="header-buttons">
          <el-button
            class="el-drawer__close-btn"
            :icon="Close"
            @click="handleClose"
          />
        </div>
      </template>
      <el-form :model="form" label-width="auto">
        <el-form-item label="网格坐标">
          <span>
            {{ `${form.longitude},${form.latitude},${form.height}` }}
          </span>
        </el-form-item>
        <el-form-item label="网格等级">
          <span>
            {{ `第${form.gridClass}级` }}
          </span>
        </el-form-item>
        <el-form-item label="所属层级">
          <span>
            {{ `第${form.layer}层` }}
          </span>
        </el-form-item>
        <!-- 可编辑区域 -->
        <el-form-item label="网格容量">
          <el-input v-model="form.capacity" />
        </el-form-item>
        <el-form-item label="网格流量">
          <el-input v-model="form.flow" />
        </el-form-item>
        <el-form-item label="拥挤等级">
          <el-input v-model="form.congestion" />
        </el-form-item>
        <!-- <el-form-item label="网格类型">
          <el-input v-model="form.areoTypeName" />
        </el-form-item> -->
        <el-form-item label="网格类型">
          <el-select
            v-model="form.areoType"
            placeholder="请选择网格类型"
            popper-class="airgrid-edit-proper"
          >
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="空域网联环境">
          <el-input v-model="form.env" />
        </el-form-item>
        <el-form-item label="噪音">
          <el-input v-model="form.noise" />
        </el-form-item>
        <el-form-item label="风速">
          <el-input v-model="form.speed" />
        </el-form-item>
        <el-form-item label="风险">
          <el-input v-model="form.risk" />
        </el-form-item>
        <el-form-item label="费用">
          <el-input v-model="form.cost" />
        </el-form-item>
        <el-form-item label="人口密度">
          <el-input v-model="form.people" />
        </el-form-item>
        <el-form-item label="作业类型">
          <el-input v-model="form.activity" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, toRefs, watch, onMounted } from "vue";
import { VcEntity, VcGraphicsBox, VcPrimitive } from "vue-cesium";
import { ElMessage } from "element-plus";
import { Edit, Close } from "@element-plus/icons-vue";
import api from "@/api";
import statistics from "@/api/statistics";

const props = defineProps({
  visible: Boolean,
});

const { visible } = toRefs(props);

const airGridTypes = ref([]);
const showAirGridTypes = ref([]);
const airGrids = ref([]);
const drawerVisible = ref(false);
const editing = ref(false);
const form = ref(null);
const geometryInstances = ref([]);
const primitiveAppearance = ref(null);
const primitiveKey = ref(0);

onMounted(async () => {
  const result = await statistics.getLayers();
  if (result.code === 200) {
    airGridTypes.value = result.data || [];
  }
});

watch(visible, (newValue, oldValue) => {
  if (!newValue) {
    airGrids.value = [];
    geometryInstances.value = [];
    showAirGridTypes.value = [];
  }
});

watch(
  showAirGridTypes,
  (newValue, oldValue) => {
    if (newValue.length > 0) {
      getAirGrids();
    } else {
      airGrids.value = [];
      geometryInstances.value = [];
    }
  },
  { deep: true }
);

watch(
  airGrids,
  () => {
    updateGeometryInstances();
  },
  { deep: true }
);

const getPosition = (val) => {
  return { lng: val.longitude, lat: val.latitude, height: val.height };
};

const getDimensions = (val) => {
  return { x: val.edgeLength, y: val.edgeLength, z: val.edgeLength };
};

const getAirGrids = async () => {
  try {
    const requests = showAirGridTypes.value.map((item) => api.getAirGrid(item));
    const results = await Promise.all(requests);
    const allGrids = results.flatMap((result) => {
      if (result.code === 200) {
        return result.data || [];
      } else {
        ElMessage.error(result.msg || "服务器忙，请稍后重试！");
        return [];
      }
    });
    airGrids.value = allGrids;
  } catch (error) {
    ElMessage.error("请求失败，请稍后重试！");
  }
};

const updateGeometryInstances = () => {
  geometryInstances.value = airGrids.value.map((grid) => {
    const dimensions = new Cesium.Cartesian3(
      grid.edgeLength / 2,
      grid.edgeLength / 2,
      grid.edgeLength / 2
    );
    const position = Cesium.Cartesian3.fromDegrees(
      grid.longitude,
      grid.latitude,
      grid.height
    );
    // const modelMatrix = Cesium.Matrix4.fromTranslation(position)
    const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
    return new Cesium.GeometryInstance({
      id: grid.id,
      geometry: new Cesium.BoxGeometry({
        vertexFormat: Cesium.VertexFormat.POSITION_AND_NORMAL,
        maximum: dimensions,
        minimum: new Cesium.Cartesian3(
          -grid.edgeLength / 2,
          -grid.edgeLength / 2,
          -grid.edgeLength / 2
        ),
      }),
      modelMatrix: modelMatrix,
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          Cesium.Color.fromCssColorString(grid.areoTypeColor)
        ),
      },
    });
  });

  primitiveKey.value += 1;

  primitiveAppearance.value = new Cesium.PerInstanceColorAppearance({
    flat: true,
    translucent: true,
  });
};

// 类型选择框
const typeList = ref([]);

const handleEdit = async () => {
  const { data } = await api.getAriGridType();
  typeList.value = data;
  drawerVisible.value = true;
};

const handleClose = () => {
  drawerVisible.value = false;
  form.value = null;
};

const handleFocus = (e) => {
  const id = e.pickedFeature.id;
  const grid = airGrids.value.find((item) => item.id === id);
  if (grid) {
    // drawerVisible.value = true
    form.value = grid;
  }
};

const handleBlur = () => {
  drawerVisible.value = false;
  form.value = null;
};

const handleConfirm = async () => {
  const result = await api.updateAirGrid(form.value);
  if (result.code === 200) {
    ElMessage.success({
      message: result.msg || "修改成功！",
      onClose: () => {
        // form.value = null;
        editing.value = false;
        drawerVisible.value = false;
        airGrids.value = airGrids.value.map((item) => {
          if (item.id === form.value.id) {
            return form.value;
          }
          return item;
        });
      },
    });
  } else {
    ElMessage.error(result.msg || "服务器忙，请稍后重试！");
  }
};
</script>

<style scoped></style>
